package tutor.mina.server;

import java.lang.management.ManagementFactory;
import java.net.InetSocketAddress;
import java.util.Date;

import javax.management.ObjectName;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.mina.common.IoAcceptor;
import org.apache.mina.common.IoHandlerAdapter;
import org.apache.mina.common.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.integration.jmx.IoServiceMBean;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;

public class JMXTimeServer {

    static Log log = LogFactory.getLog( JMXTimeServer.class );

    public static void main( final String[] args ) {
        final IoAcceptor acceptor = new NioSocketAcceptor();

        acceptor.setHandler( new IoHandlerAdapter() {

            @Override
            public void sessionOpened( final IoSession session )
                throws Exception {
                session.write( new Date() );
            };

        } );

        acceptor.getFilterChain().addLast( "codec",
                new ProtocolCodecFilter( new TextLineCodecFactory() ) );
        acceptor.getFilterChain().addLast( "logging", new LoggingFilter() );

        try {
            ManagementFactory.getPlatformMBeanServer().registerMBean(
                    new IoServiceMBean( acceptor ),
                    new ObjectName( "tutor.mina.server:type=IoServiceMBean" ) );

            acceptor.bind( new InetSocketAddress( 8150 ) );
        }
        catch( final Exception e ) {
            log.error( "Error:", e );
        }
    }
}
